package com.gjp.processdemo.utils;

import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ImageUtil {

    /**
     * 将inputStream转换为base64图片
     * @param is
     * @return
     * @throws IOException
     */
    public static String handleInputStream2Base64(InputStream is) throws IOException {
        BufferedImage bi = ImageIO.read(is);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bi, "png", baos);
        byte[] data = baos.toByteArray();
        BASE64Encoder encoder = new BASE64Encoder();
        String base64ImageData = encoder.encode(data);
        is.close();
        //去除回车符
        base64ImageData = base64ImageData.replace("\r\n","");
        return "data:image/png;base64," + base64ImageData;
    }
}
